﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microhard.FMCG.Buz.Impls.KASystem.WUMart;
using System.IO;
using Microhard.FMCG.Buz.Interfaces;

namespace Microhard.FMCGClient
{
    public partial class frmLogin : Form
    {
        private Guid _runningInstance;
        public frmLogin()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            this.cbSystemSelect.Items.Clear();
            this.cbSystemSelect.Items.Add("WUMART");
        }

        private void cbSystemSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectedSystemName = this.cbSystemSelect.SelectedItem.ToString();
            bool isRunning;
            var stream = RunningMonitor.Monitor.Prepare(selectedSystemName, out _runningInstance, out isRunning);
            if (stream != null)
            {
                var image = Image.FromStream(stream);
                this.pbLoginCode.Image = image;
                this.panelLogin.Show();
            }
            else
            {
                frmMain main = this.ParentForm as frmMain;
                if (isRunning)
                {
                    main.ToNotifiUI(new NotifiUIModel { text = string.Format(ResMessage.DuplicateAccount, this.cbSystemSelect.Text) });
                }
                else
                {
                    main.ToNotifiUI(new NotifiUIModel { text = string.Format(ResMessage.KASystemError, this.cbSystemSelect.Text) });
                }

            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            RunningMonitor.Monitor.IsLogin = true;
            RunningMonitor.Monitor.Add(new KASystemRunningModel
            {
                UserName = this.txbuserName.Text,
                Passowrd = this.txbPassword.Text,
                ValidCode = this.txbCode.Text,
                System = this.cbSystemSelect.Text
            }, _runningInstance);
            frmMain main = this.ParentForm as frmMain;
            if (main != null)
            {
                main.ToNotifiUI(new NotifiUIModel { text = string.Format(ResMessage.Running, this.cbSystemSelect.Text) });
            }
            this.Close();
        }

    }
}
